﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySQL.Db;

namespace Gollie.Controls
{
	public partial class ReviewVendor : BaseUserControl
	{
		DateTime visitDate = DateTime.MinValue;
		uint customerId = 0;
		uint vendorId = 0;
		bool ok = false;

		protected void Page_Load(object sender, EventArgs e)
		{
			
		}

		protected override void PreLoadHandler(object sender, EventArgs e)
		{
			try
			{
				string id = Request["id"];
				Ticket ticket = new Ticket(id);

				ticket.PopHash();
				visitDate = ticket.PopDateTime();
				customerId = ticket.PopUInt32();
				vendorId = ticket.PopUInt32();
			}
			catch (Exception)
			{
				this.pnlInvalidTicket.Visible = true;

				return;
			}

			if (visitDate.AddDays(7) < DateTime.Now)
			{
				this.pnlExpired.Visible = true;

				return;
			}

			ResultSet r = Database.Queries.GetReview(customerId, vendorId, visitDate);
			if (r.Count > 0)
			{
				pnlAlreadyReviewed.Visible = true;

				return;
			}

			ok = true;
		}

		protected override void OnPostBack(object sender, EventArgs e)
		{
			if (!ok)
				return;

			string comment = this.tbComment.Text;
			if (comment.Length > 0)
			{
				comment = HttpUtility.HtmlEncode(comment);
			}

			uint rating = GetRating();

			Database.Queries.InsertReview(customerId, vendorId, visitDate, rating, comment.Length == 0 ? null : comment);

			pnlThanks.Visible = true;
			pnlFirstHit.Visible = false;
		}

		private uint GetRating()
		{
			if (rb1.Checked) return 1;
			if (rb2.Checked) return 2;
			if (rb3.Checked) return 3;
			if (rb4.Checked) return 4;

			return 5;
		}

		protected override void OnFirstHit(object sender, EventArgs e)
		{
			if (!ok)
				return;

			//setting attr in ascx doesn't work
			this.tbComment.Attributes.Add("maxlength", "1024");

			pnlReview.Visible = true;

			this.SetVendor(vendorId);
		}

		private void SetVendor(uint vendorId)
		{
			VendorInfo vendor = VendorInfo.GetVendorInfo(vendorId);

			VendorPresenterFull vendorPresenterFull = LoadControl("VendorPresenterFull.ascx") as VendorPresenterFull;
			vendorPresenterFull.VendorId = vendorId;

			this.pnlVendorPresenter.Controls.AddAt(0, vendorPresenterFull);

			this.lblVendorName.Text = vendor.BedrijfsNaam;
		}
	}
}